"use strict";
const semver = require("semver");
const axios = require("axios");
const urlJoin = require("url-join");

async function getSemverVersions(pkgName, registry) {
  if (!pkgName) {
    return [];
  }
  registry = registry || getDefaultRegistry();
  const requestUrl = urlJoin(registry, pkgName);
  const result = await axios.get(requestUrl);
  if (result.status === 200 && result.data && result.data.versions) {
    return Object.keys(result.data.versions);
  }
  return [];
}

function getDefaultRegistry(isOriginal) {
  return isOriginal
    ? "https://registry.npmjs.org"
    : "https://registry.npm.taobao.org";
}

function getRecentVersions(baseVersion, versions) {
  return versions
    .filter((version) => semver.satisfies(version, `>=${baseVersion}`))
    .sort((a, b) => semver.gte(b, a));
}

async function getNpmLastVersion(baseVersion, pkgName, registery) {
  const versions = await getSemverVersions(pkgName, registery);
  let recentVersions = getRecentVersions(baseVersion, versions);
  if (recentVersions && recentVersions.length) {
    return recentVersions[0];
  }
  return "";
}

module.exports = {
  getSemverVersions,
  getNpmLastVersion,
};
